//
//  DynamicTextView.m
//  CareRing
//
//  Created  on 2024/12/12.
//
    

#import "DynamicTextView.h"
#import <Masonry/Masonry.h>
@interface DynamicTextView () <UITextViewDelegate>

@property (nonatomic, strong) NSMutableArray *textArray; // 存储所有文本
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) UITextView *txtView;

@end

@implementation DynamicTextView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.txtView = [[UITextView alloc]init];
        [self addSubview:self.txtView];
        [self.txtView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.top.equalTo(self);
            make.bottom.equalTo(self);
        }];
        // 基本设置
        self.txtView.font = [UIFont systemFontOfSize:16];
        self.txtView.editable = NO;
        self.backgroundColor = [UIColor whiteColor];
        self.txtView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        // 初始化数据
        self.textArray = [NSMutableArray array];
        self.currentPage = 0;
        self.pageSize = 2000; // 每页显示的文本条数
        
        // 设置代理以监听滚动
        self.txtView.delegate = self;
    }
    return self;
}

-(void)setFont:(UIFont *)font
{
    self.txtView.font = font;
}


- (void)addNewText:(NSString *)text
{
    if (!text) {
        return;
    }
    // 添加新文本到数组
    [self.textArray addObject:text];
    [self appendText:text];
    // 如果当前是最后一页，则显示新文本
//    if (self.currentPage == (self.textArray.count - 1) / self.pageSize) {
//            [self appendText:text];
//    }
}

- (void)appendText:(NSString *)text {
    if (self.txtView.text.length > 0) {
        self.txtView.text = [NSString stringWithFormat:@"%@\n%@", self.txtView.text, text];
    } else {
        self.txtView.text = text;
    }
    [self.txtView scrollRangeToVisible:NSMakeRange(self.txtView.text.length, 0)];
}

- (void)loadPage:(NSInteger)page {
    NSInteger startIndex = page * self.pageSize;
    NSInteger endIndex = MIN((page + 1) * self.pageSize, self.textArray.count);
    
    NSMutableString *pageText = [NSMutableString string];
    for (NSInteger i = startIndex; i < endIndex; i++) {
        [pageText appendString:self.textArray[i]];
        if (i < endIndex - 1) {
            [pageText appendString:@"\n"];
        }
    }
    
    self.txtView.text = pageText;
    self.currentPage = page;
}

- (void)clearAllText
{
    self.txtView.text = @"";  // 清空文本内容
    [self.textArray removeAllObjects];
}
// UITextViewDelegate 方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 当滚动到顶部时，加载上一页
    if (scrollView.contentOffset.y <= 0 && self.currentPage > 0) {
        [self loadPage:self.currentPage - 1];
    }
}

@end
